/**
*@ClassName: SysUserController
*@Description
*@Author maozhi
*@Date 2021/3/22
*@Time 14:39
*/
package com.universityJob.modules.data.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.universityJob.common.annotation.SysLog;
import com.universityJob.common.exception.RRException;
import com.universityJob.common.utils.*;

import com.universityJob.modules.data.entity.DataUserEntity;

import com.universityJob.modules.data.service.DataUserService;
import com.universityJob.modules.sys.controller.AbstractController;

import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 用户
 *
 * @author Mark
 */
@RestController
@RequestMapping("/data/user")
public class DataUserController extends AbstractController {
	@Autowired
	private DataUserService dataUserService;

	/**
	 * 存储请求产生的文件名
	 */
	Map<String, String> fileInfo = new HashMap<>();
	@Value("${upload.file}excel/")
	String excelPath;
	private Logger logger = LoggerFactory.getLogger(getClass());
	/**
	 * 所有用户列表
	 */
	@GetMapping("/list")
	@RequiresPermissions("sys:user:list")
	public R list(@RequestParam Map<String, Object> params){

		PageUtils page = dataUserService.queryPage(params);

		return R.ok().put("page", page);
	}



	/**
	 * 用户信息
	 */
	@GetMapping("/info/{userId}")
	@RequiresPermissions("sys:user:info")
	public R info(@PathVariable("userId") Long userId){
		DataUserEntity user = dataUserService.getById(userId);
		return R.ok().put("user", user);
	}
	/**
	 * 用户信息
	 */
	@GetMapping("/findByUsername/{username}")
	@RequiresPermissions("sys:user:info")
	public R info(@PathVariable("username") String username){
		QueryWrapper<DataUserEntity> objectQueryWrapper = new QueryWrapper<>();
		objectQueryWrapper.eq("username",username);
		DataUserEntity user = dataUserService.getOne(objectQueryWrapper);


		return R.ok().put("user", user);
	}
	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@PostMapping("/save")
	@RequiresPermissions("sys:user:save")
	public R save(@RequestBody DataUserEntity user){

		R r = dataUserService.saveUser(user);

		return r;
	}

	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@PostMapping("/update")
	@RequiresPermissions("sys:user:update")
	public R update(@RequestBody DataUserEntity user){

		R r = dataUserService.update(user);

		return r;
	}

	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@PostMapping("/delete")
	@RequiresPermissions("sys:user:delete")
	public R delete(@RequestBody Long[] userIds){
		R r = dataUserService.deleteBatch(userIds);

		return r;
	}
	/**
	 * 导入数据
	 */
	@PostMapping("/inputExcel")
	@RequiresPermissions("sys:user:save")
	public R inputExcel(HttpServletResponse response, @RequestBody Map<String, Object> params) throws Exception {
		//向前端返回的数据
		Map<String, Object> data = new HashMap<>();
		String uid = UUID.randomUUID().toString().replaceAll("-", "");
		this.fileInfo.put(uid, "-1");
		data.put("uid", uid);
		data.put("fileName","");
		params.put("uid", uid);
		logger.info("开始导入数据");
		Thread thread = new Thread(() -> {
			try {
				int i = dataUserService.inputExcel(response, params);
				this.fileInfo.put(uid, String.valueOf(i));
				logger.info("数据导入成功！");
			} catch (Exception e) {
				logger.error("数据导入出错！");
			}
		});
		thread.start();

		return R.ok(data);
	}
	/**
	 * 导出excel
	 */
	@PostMapping("/exportExcel")
	@RequiresPermissions("sys:user:save")
	public R exportExcel(HttpServletResponse response, @RequestBody Map<String, Object> params) throws Exception {
		//向前端返回的数据
		Map<String, Object> data = new HashMap<>();
		String uid = UUID.randomUUID().toString().replaceAll("-", "");
		this.fileInfo.put(uid, "0");
		data.put("uid", uid);
		data.put("fileName", params.get("fileName"));
		params.put("path", excelPath);
		params.put("uid", uid);
		logger.info("开始准备Excel文件：{}",params.get("fileName"));
		Thread thread = new Thread(() -> {
			try {
				int i = dataUserService.exportStatisticsReport(response, params);
				this.fileInfo.put(uid, String.valueOf(i));
				logger.info("文件已经准备好，准备开始下载！");
			} catch (Exception e) {
				logger.error("文件导出出错！");
			}
		});
		thread.start();

		return R.ok(data);
	}
	/**
	 * 循环请求接口
	 */
	@PostMapping("/testpolling")
	@ResponseBody
	public R testPolling(@RequestBody Map<String, Object> param) {
		String uid = ExportExcel.nvll(param.get("uid"));
		String fileName = ExportExcel.nvll(param.get("fileName"));
		Map<String, Object> pollingData = new HashMap<>();
		pollingData.put(uid, fileInfo.get(uid));
		pollingData.put("fileName", fileName);
		return R.ok(pollingData);
	}
	/**
	 * 最后下载的接口
	 */
	@RequestMapping("/testdownload")
	@ResponseBody
	public void testDownload(HttpServletResponse response, @RequestParam Map<String, Object> param) {
		String fileName = (String) param.get("fileName");
		String uid = ExportExcel.nvll(param.get("uid"));
		String uidFolder = excelPath + uid;
		try {
			InputStream bis = new BufferedInputStream(new FileInputStream(new File(uidFolder + "/" + fileName)));
			fileName = URLEncoder.encode(fileName, "UTF-8");
			// 设置文件下载头
			response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
			// 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
			response.setContentType("multipart/form-data;charset=utf-8");
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			int len = 0;
			byte[] buf = new byte[2048];
			while ((len = bis.read(buf)) != -1) {
				out.write(buf, 0, len);
			}
			bis.close();
			out.close();
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//删除临时文件和文件信息
			FileUtil.deleteDirectory(uidFolder);
			fileInfo.remove(uid);
		}
	}
}
